package logic

import (
	"context"
	"errors"
	"shops/cache"
	"shops/models"
	"shops/shoprpc/internal/svc"
	"shops/shoprpc/shoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *shoprpc.LoginRequest) (*shoprpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	models.DB.Where("account=?", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, errors.New("用户名不存在，请重新输入")
	}
	if in.Account == "" || in.Password == "" {
		return nil, errors.New("手机号和密码不能为空")
	}
	if in.CaptchaCode == "" {
		return nil, errors.New("验证码不能为空")
	}
	cachejson, _ := cache.Rdb.Get(cache.Ctx, "captcha"+in.Account).Result()
	if in.CaptchaCode != cachejson {
		return nil, errors.New("图形验证码错误，请重新输入")
	}
	data, _ := cache.Rdb.Get(cache.Ctx, "sendSms"+in.Account).Result()
	if in.SendSmsCode != data {
		return nil, errors.New("短信验证码错误，请重新输入")
	}
	return &shoprpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
